// import { addRule, removeRule, rule, updateRule } from '@/services/api/auth';
import { getDeptList } from '@/services/api/dept';
import { DeptResultItem } from '@/services/api/model/deptModel';
import { UserResultItem } from '@/services/api/model/usersModel';
import { delItem, getUserList } from '@/services/api/users';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Card, Popconfirm } from 'antd';
import Tree, { DataNode, TreeProps } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import FormModal from './components/CreateForm';
const TreeLeft: React.FC<{
  treeData: DataNode[];
}> = (props) => {
  const { treeData } = props;
  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };

  return (
    <Tree
      autoExpandParent={true}
      showLine={true}
      fieldNames={{
        title: 'name',
        key: 'id',
      }}
      checkable
      onSelect={onSelect}
      onCheck={onCheck}
      treeData={treeData}
    />
  );
};
const Users: React.FC = () => {
  const actionRef = useRef<ActionType>();
  //提交
  const onSubmit = () => {
    // 重置到默认值，包括表单
    // 断言标识,reloadAndRest一定是存在的
    actionRef.current!.reloadAndRest!();
  };

  // 删除
  const handleConfirm = async (userIds: number) => {
    // 这里 return 一个 primise 之后会执行异步关闭 resolve(null) 之后关闭
    try {
      await delItem({
        userIds,
      });
      actionRef.current!.reloadAndRest!();
      Promise.resolve(null);
    } catch (error) {
      Promise.resolve(null);
    }
  };
  const [tableData, setTableData] = useState<DeptResultItem[]>([]);
  useEffect(() => {
    getDeptList().then((res) => {
      setTableData(res.data);
    });
  }, []);
  const columns: ProColumns<UserResultItem>[] = [
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'username',
    },
    {
      title: '手机',
      dataIndex: 'phone',
      align: 'center',
    },
    {
      title: '部门信息',
      align: 'center',
      dataIndex: 'deptName',
    },
    {
      title: '角色信息',
      align: 'center',
      dataIndex: 'roleNames',
    },
    {
      title: '性别',
      align: 'center',
      dataIndex: 'sex',
      valueType: 'select',
      valueEnum: {
        1: {
          text: '男',
        },
        0: {
          text: '女',
        },
      },
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <FormModal
          tableData={tableData}
          trigger={<Button type="text">编辑</Button>}
          onSubmit={onSubmit}
          key={'edit'}
          title="编辑"
          userId={record.id}
        ></FormModal>,
        <Popconfirm key={'del-1'} title="确定删除吗" onConfirm={() => handleConfirm(record.id!)}>
          <Button key={'del1'} danger style={{ width: '100%' }} size="small" type="text">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<UserResultItem, API.PageParams>
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Card>
              <TreeLeft treeData={tableData as unknown as DataNode[]}></TreeLeft>
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <FormModal tableData={tableData} key={'add'} onSubmit={onSubmit}></FormModal>,
        ]}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: API.PageParams & API.CurrentParams,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await getUserList({
            page: params.current,
            pageSize: params.pageSize,
          });
          return {
            data: msg.data.list,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: msg.data.total,
          };
        }}
        columns={columns}
      />
    </PageContainer>
  );
};
export default Users;
